/*
 * Copyright (c) 2015 DHC Corporation.
 */
package cn.com.dhc.danlu.util;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import android.Manifest;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.ClipboardManager;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.tbruyelle.rxpermissions.RxPermissions;
import com.umeng.analytics.MobclickAgent;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.MainMenuActivity;
import cn.com.dhc.danlu.dlware.global.DanluApplication;
import cn.com.hd.mall.web.common.ThreeTuple;
import cn.com.hd.mall.web.common.Tuple;
import rx.Subscriber;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * 共通方法
 *
 * @author MuWei
 * @version 1.00 2015/02/03 新建
 */
public class CommonUtils {
    private static long lastClickTime;

    /**
     * 判断是否是手机号码
     */
    public static boolean isMobileNumber(String number) {
        return Pattern.compile("^((\\(\\d{3}\\))|(\\d{3}\\-))?(1[23456789]\\d{9})$").matcher(number).matches();
    }

    /**
     * 获取状态栏高度
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * Dip转为像素
     *
     * @param context
     *         Context
     * @param dip
     *         Dip
     *
     * @return 像素
     */
    public static int dipToPx(Context context, int dip) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
    }

    /**
     * 把单个英文字母或者字符串转换成数字ASCII码
     */
    public static int character2ASCII(String input) {
        char[] temp = input.toCharArray();
        StringBuilder builder = new StringBuilder();
        for (char each : temp) {
            builder.append((int) each);
        }
        String result = builder.toString();
        return Integer.parseInt(result);
    }

    /**
     * 汉字转为汉语拼音
     *
     * @param chinese
     *         汉字
     *
     * @return 汉语拼音
     */
    public static String converterToPinYin(String chinese) {
        String pinyinString = "";
        char[] charArray = chinese.toCharArray();
        // 根据需要定制输出格式，用默认的即可
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        try {
            // 遍历数组，ASC码大于128进行转换
            for (char aCharArray : charArray) {
                if (aCharArray >= 0x3400 && aCharArray <= 0x9FBB) {
                    // charAt(0)取出首字母
                    pinyinString += PinyinHelper.toHanyuPinyinStringArray(aCharArray, defaultFormat)[0].charAt(0);
                } else {
                    pinyinString += aCharArray;
                }
            }
            return pinyinString;
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 隐藏软键盘。
     */
    public static void hideSoftInputFromWindow(Context context, View view) {
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    public static void hideSoftInputForce(Activity activity) {
        if (activity.getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (activity.getCurrentFocus() != null) {
                InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 弹出软键盘。
     */
    public static void showSoftInputFromWindow(Context context, View view) {
        view.requestFocus();
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
    }

    /**
     * 判断SD卡是否可用
     *
     * @return SD卡是否可用
     */
    public static boolean existSDCard() {
        // 获取SD卡状态
        String status = Environment.getExternalStorageState();
        // 判断SD卡是否为存在状态
        return status.equalsIgnoreCase(Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取名字的第一个字母
     *
     * @param name
     *         用户名
     *
     * @return 名字的第一个字母
     */
    public static String getFirstLetter(String name) {
        Pattern pattern = Pattern.compile("[a-zA-Z]");
        Matcher matcher = pattern.matcher(name);
        // 名字中包含汉字或英文字母
        if (matcher.find()) {
            // 获取名字的第一个字母
            return matcher.group();
        } else {
            // 当名字不包括任何字母或汉字时返回标记位#
            return CommonConst.FIRST_NAME_LETTER;
        }
    }

    /**
     * 实现文本复制功能
     *
     * @param content
     *         要复制的文本
     * @param context
     *         Context
     */
    public static void copy(String content, Context context) {
        // 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(content.trim());
    }

    /**
     * 获取Android系统版本号。
     */
    public static String getVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 获取角色代码
     *
     * @param role
     *         角色
     *
     * @return 角色代码
     */
    public static int getRole(String role) {
        role = role.toUpperCase();

        int roleCode = 0;

        if (CommonConst.LoginCustomerRole.B_R_ADMI.equals(role)) {
            // 配送商(管理员)
            roleCode = CommonConst.LoginCustomerRole.ROLE_ADMI;
        } else if (CommonConst.LoginCustomerRole.B_R_PURC.equals(role)) {
            // 配送商(采购员)
            roleCode = CommonConst.LoginCustomerRole.ROLE_PURC;
        } else if (CommonConst.LoginCustomerRole.B_R_SALE.equals(role)) {
            // 配送商(销售员)
            roleCode = CommonConst.LoginCustomerRole.ROLE_SALE;
        } else if (CommonConst.LoginCustomerRole.T_ROLE.equals(role)) {
            // 终端店
            roleCode = CommonConst.LoginCustomerRole.ROLE_TERMINAL;
        }

        return roleCode;
    }

    /**
     * 是否为终端店角色
     *
     * @param role
     *         角色
     *
     * @return 是否为终端店角色
     */
    public static boolean isTerminalRole(String role) {
        role = role.toUpperCase();

        boolean isTerminalRole = false;

        if (CommonConst.LoginCustomerRole.B_R_ADMI.equals(role)) {
            // 配送商(管理员)
            isTerminalRole = false;
        } else if (CommonConst.LoginCustomerRole.B_R_PURC.equals(role)) {
            // 配送商(采购员)
            isTerminalRole = false;
        } else if (CommonConst.LoginCustomerRole.B_R_SALE.equals(role)) {
            // 配送商(销售员)
            isTerminalRole = false;
        } else if (CommonConst.LoginCustomerRole.T_ROLE.equals(role)) {
            // 终端店
            isTerminalRole = true;
        }

        return isTerminalRole;
    }

    /**
     * 获取订单状态
     *
     * @param context
     *         Context
     * @param statusCode
     *         订单状态Code
     *
     * @return 订单状态
     */
    public static String getOrderStatus(Context context, String statusCode) {
        // 订单状态
        String statusValue = "";
        // 订单Code数组
        String[] statusCodes = context.getResources().getStringArray(R.array.order_status_code);
        // 订单值数组
        String[] statusValues = context.getResources().getStringArray(R.array.order_status_value);

        // Code与值相互匹配
        if (statusCodes.length == statusValues.length) {
            int position = 0;

            for (int i = 0; i < statusCodes.length; i++) {
                // Code与值一一对应
                if (statusCode.equalsIgnoreCase(statusCodes[i])) {
                    position = i;
                    break;
                }
            }

            // 获取值
            statusValue = statusValues[position];
        }

        return statusValue;
    }

    public static boolean isValidTerminalName(String name) {
        String reg = "^[a-zA-Z0-9_\\u4e00-\\u9fa5]+$";
        return patternMatch(name, reg);
    }

    /**
     * 新密码规则匹配
     */
    public static boolean checkNewPasswordRule(String password) {
        return patternMatch(password, PatternConstants.PATTERN_NEW_PASSWORD_RULE);
    }

    /**
     * 正则表达式匹配
     *
     * @param string
     *         要匹配的字符串
     * @param pattern
     *         正则表达式
     *
     * @return 是否匹配(true:匹配; false:不匹配)
     */

    public static boolean patternMatch(String string, String pattern) {
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(string);
        return m.matches();
    }

    /**
     * 用户名校验规则：由3-30位数字字母及下划线组成，以字母开头
     */
    public static boolean checkUserNameRule(String username) {
        return TextUtils.isEmpty(username) || patternMatchFind(username, "^[0-9a-zA-Z\u4e00-\u9fa5_]{3,30}$");
    }

    public static boolean patternMatchFind(String string, String pattern) {
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(string);
        return m.find();
    }

    /**
     * 匹配数字0-9
     */
    public static boolean isNumber(String number) {
        // 用户名为空
        return !isStringBlank(number) && patternMatch(number, PatternConstants.PATTERN_NUM);
    }

    /**
     * 判断字符串变量是否为空
     */
    public static boolean isStringBlank(String str) {
        return TextUtils.isEmpty(str);
    }

    /**
     * 匹配联系电话含-和手机号
     */
    public static boolean isTelNumber(String number) {
        // 用户名为空
        return !isStringBlank(number) && patternMatch(number, PatternConstants.PATTERN_TEL);
    }

    /**
     * 注册密码规则匹配
     */
    public static boolean checkPassWordRule(String ps) {
        // 注册密码为空
        return !isStringBlank(ps) && patternMatchFind(ps, PatternConstants.PATTERN_PWD_RULE);
    }

    /**
     * 手机验证码校验
     */
    public static boolean checkVerificateRule(String ver) {
        // 手机验证码为空
        return !isStringBlank(ver) && ver.length() == 4;
    }

    /**
     * 分转成元
     */
    public static BigDecimal fenToYuan(BigDecimal fenValue) {
        BigDecimal divide = fenValue.divide(new BigDecimal(100));
        // 如果是小数 就保留两位小数（四舍五入）
        String s = CalculatePriceUtil.roungDown(divide);
        divide = new BigDecimal(s);
        return divide;
    }

    /**
     * 元转分
     */
    public static BigDecimal yuanToFen(BigDecimal yuanValue) {
        return yuanValue.multiply(new BigDecimal(100));
    }

    /***
     * 茶类缓存
     */
    public static Tuple<String, String> cachingCategoryCode(Context context, String categoryCode, String categoryName) {
        Tuple<String, String> tuple = new Tuple<>(categoryCode, categoryName);
        ACache aCache = ACache.get(context);
        aCache.put(CommonConst.ACacheComstants.CATEGORY, tuple);
        return tuple;
    }

    /**
     * 将属性放入缓存体中
     *
     * @param context
     *         上下文
     * @param belongsTo
     *         属性类
     * @param propertyCode
     *         属性码
     * @param propertyName
     *         属性名
     */
    public static CachingArrayList cachingPropertyCode(Context context, String belongsTo, String propertyCode, String propertyName) {
        ThreeTuple<String, String, String> tuple = new ThreeTuple<>(belongsTo, propertyCode, propertyName);

        ACache aCache = ACache.get(context);
        Object propertyObj = aCache.getAsObject(CommonConst.ACacheComstants.PROPERTY);
        if (propertyObj == null) {
            CachingArrayList cachingArrayList = new CachingArrayList();
            cachingArrayList.add(tuple);
            aCache.put(CommonConst.ACacheComstants.PROPERTY, cachingArrayList);
            return cachingArrayList;
        } else {
            CachingArrayList propertyList = (CachingArrayList) propertyObj;
            propertyList.add(tuple);
            aCache.put(CommonConst.ACacheComstants.PROPERTY, propertyList);
            return propertyList;
        }
    }

    /**
     * 缓存品牌码与品牌名
     *
     * @param context
     *         上下文
     * @param brandId
     *         品牌码
     * @param brandName
     *         品牌名
     *
     * @return 品牌码与品牌名的缓存体
     */
    public static Tuple<String, String> cachingBrandId(Context context, String brandId, String brandName) {
        Tuple<String, String> tuple = new Tuple<>(brandId, brandName);
        ACache aCache = ACache.get(context);
        aCache.put(CommonConst.ACacheComstants.BRAND, tuple);
        return tuple;
    }

    /**
     * 将价格放入到缓存
     *
     * @param context
     *         上下文
     * @param price
     *         价格值
     */
    public static void cachingPrice(Context context, String price) {
        ACache aCache = ACache.get(context);
        aCache.put(CommonConst.ACacheComstants.PRICE, price);
    }

    /**
     * 获取缓存中的行数
     */
    @SafeVarargs
    public static Tuple<Integer, Integer> getAcacheIndex(Tuple<String, String> cachedTuple, List<Tuple<String, String>>... lists) {
        if (cachedTuple == null) {
            return null;
        }

        for (int i = 0; i < lists.length; i++) {
            List<Tuple<String, String>> list = lists[i];
            for (int j = 0; j < list.size(); j++) {
                Tuple<String, String> tuple = list.get(j);
                if (cachedTuple.getFirstValue().equals(tuple.getFirstValue()) && cachedTuple.getSecondValue().equals(tuple.getSecondValue())) {
                    return new Tuple<>(i, j);
                }
            }
        }
        return null;
    }

    /***
     * 清除所有缓存
     */
    public static boolean clearAllCgrPrtBrd(Context context) {
        ACache aCache = ACache.get(context);
        aCache.remove(CommonConst.ACacheComstants.CATEGORY);
        aCache.remove(CommonConst.ACacheComstants.PROPERTY);
        aCache.remove(CommonConst.ACacheComstants.BRAND);
        aCache.remove(CommonConst.ACacheComstants.PRICE);
        return true;
    }

    /**
     * 判断两个日期是否是同一天
     */
    public static boolean isSameDay(String date1, String date2) {
        return date1.substring(0, 10).equals(date2.substring(0, 10));
    }

    /**
     * android 读取渠道号
     */
    static String readChannelFromApkMetaInfo(Context context) {
        String channel = null;
        String sourceDir = context.getApplicationInfo().sourceDir;
        final String start_flag = "META-INF/channel_";
        ZipFile zipfile = null;
        try {
            zipfile = new ZipFile(sourceDir);
            Enumeration<?> entries = zipfile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                String entryName = entry.getName();
                if (entryName.contains(start_flag)) {
                    channel = entryName.replace(start_flag, "");
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipfile != null) {
                try {
                    zipfile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return channel;
    }

    public static String parseBean2Json(Object bean) {
        Gson gson = new Gson();
        return gson.toJson(bean);
    }

    public static <T> T parseJson2Bean(String json, Class<T> clazz) {
        Gson gson = new Gson();
        return gson.fromJson(json, clazz);
    }

    public static <T> List<T> parseJsonToList(String jsonArray) {
        Gson gson = new Gson();
        return gson.fromJson(jsonArray, new TypeToken<List<T>>() {
        }.getType());
    }

    /**
     * 解决泛型在变异期类型被擦除导致
     */
    public static <T> List<T> fromJsonArray(String json, Class<T> clazz) throws Exception {
        List<T> lst = new ArrayList<>();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        for (final JsonElement elem : array) {
            lst.add(new Gson().fromJson(elem, clazz));
        }
        return lst;
    }


    public static String filterNumber(String number) {
        number = number.replaceAll("[^(0-9)]", "");
        return number;
    }

    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        return m.find();
    }

    public static String getAppVersioName(Context context) {
        String pkName = context.getPackageName();
        PackageManager pm = context.getPackageManager();
        try {
            return pm.getPackageInfo(pkName, 0).versionName;
        } catch (NameNotFoundException e) {
            return "1.0.0";
        }
    }

    /**
     * 字符串截取 保留小数点后面两位
     */
    public static String formateRate(String rateStr) {
        DecimalFormat df = new DecimalFormat("0.00");
        String format = rateStr;
        try {
            format = df.format(new BigDecimal(rateStr));
        } catch (Exception e) {
            Log.w("@@@@ L585", "CommonUtils:formateRate() -> " + "fomate two pioint error");
        } finally {
            return format;
        }
    }

    /**
     * 判断当前Intent是否存在
     */
    public static boolean isIntentAvailable(Context context, Intent intent) {
        return context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_RESOLVED_FILTER).size() > 0;
    }

    public static void callHelp(Activity context) {
        String phone = "400-011-6666";
        callPhone(context, phone);
    }

    public static void callPhone(final Activity context, final String phone) {
        RxPermissions rxPermissions = new RxPermissions(context);
        rxPermissions.request(Manifest.permission.CALL_PHONE)
                .subscribe(new Subscriber<Boolean>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable t) {
                        ToastUtil.getInstance().show("onError");
                    }

                    @Override
                    public void onNext(Boolean granted) {
                        if (granted) {
                            if (phone != null && phone.trim().length() > 0) {
                                // 这里"tel:"+电话号码 是固定格式，系统一看是以"tel:"开头的，就知道后面应该是电话号码。
                                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone.trim()));
                                context.startActivity(intent);// 调用上面这个intent实现拨号
                            } else {
                                ToastUtil.getInstance().show("电话号码不能为空");
                            }
                        } else {
                            ToastUtil.getInstance().show("权限被拒绝");
                        }
                    }
                });
    }

    /**
     * 获取屏幕宽度
     */
    public static int getScreenWidth(Context context) {
        Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
        return display.getWidth();
    }

    /**
     * 获取屏幕高度
     */
    public static int getScreenHeight(Context context) {
        Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
        return display.getHeight();
    }

    /**
     * base64转为bitmap
     *
     * @param base64Data
     *         base64Data字符串
     *
     * @return Bitmap对象
     */
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    public static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public static void setDisAllowInputPhone(EditText et_phone, boolean isAllow) {
        if (isAllow) {
            et_phone.setFocusable(true);
            et_phone.setFocusableInTouchMode(true);
            et_phone.setFilters(new InputFilter[]{
                    new InputFilter() {
                        @Override
                        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                            return null;
                        }
                    }
            });
        } else {
            // 设置不可获取焦点
            et_phone.setFocusable(false);
            et_phone.setFocusableInTouchMode(false);
            // 输入框无法输入新的内容
            et_phone.setFilters(new InputFilter[]{
                    new InputFilter() {
                        @Override
                        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                            return source.length() < 1 ? dest.subSequence(dstart, dend) : "";
                        }
                    }
            });
        }
    }

    public static String getStringByResId(int resId) {
        return DanluApplication.get().getResources().getString(resId);
    }

    /**
     * 控制窗口背景的不透明度
     */
    public static void dimBackground(final Activity activity, float startValue, float targetValue) {
        ValueAnimator animator = ValueAnimator.ofFloat(startValue, targetValue);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float alpha = (float) animation.getAnimatedValue();
                Window window = activity.getWindow();
                WindowManager.LayoutParams layoutParams = window.getAttributes();
                layoutParams.alpha = alpha;
                window.setAttributes(layoutParams);
            }
        });
        animator.setDuration(200);
        animator.start();
    }

    /**
     * 显示不同字体颜色等操作
     */
    public static void dividerShowTextStyle(TextView textView, String text, int startIndex, int endIndex, int defaultSize, int newSize, int colorId) {
        textView.setText(getSpan(textView.getContext(), text, startIndex, endIndex, defaultSize, newSize, colorId));
    }

    public static Spannable getSpan(Context context, String text, int startIndex, int endIndex, int defaultSize, int newSize, int colorId) {
        Spannable textSpan = new SpannableStringBuilder(text);
        textSpan.setSpan(new AbsoluteSizeSpan(sp2px(context, defaultSize)), 0, startIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        textSpan.setSpan(new AbsoluteSizeSpan(sp2px(context, newSize)), startIndex, endIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        ForegroundColorSpan redSpan = new ForegroundColorSpan(context.getResources().getColor(colorId));
        textSpan.setSpan(redSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return textSpan;
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 按格式转换日期。
     *
     * @param date
     *         Date
     * @param dateFormat
     *         格式
     */
    @SuppressLint("SimpleDateFormat")
    public static String getDate(Date date, String dateFormat) {
        return new SimpleDateFormat(dateFormat).format(date);
    }

    public static void removeViewParent(@NonNull View view) {
        if (null != view.getParent()) {
            if (view.getParent() instanceof ViewGroup) {
                ViewGroup parent = (ViewGroup) view.getParent();
                parent.removeView(view);
            }
        }
    }

    public static boolean isIdCardNum(String string) {
        return patternMatch(string, "^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$");
    }

    /**
     * 判断姓名是否是中文
     */
    public static boolean checkNameChese(String name) {
        if (TextUtils.isEmpty(name)) {
            return false;
        }
        boolean res = true;
        char[] cTemp = name.toCharArray();
        for (int i = 0; i < name.length(); i++) {
            if (!isChinese(cTemp[i])) {
                res = false;
                break;
            }
        }
        return res;
    }

    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    public static String input2String(InputStream inputStream, String encode) {
        StringBuffer sb = new StringBuffer();
        byte[] b = new byte[1024];
        int len = 0;
        try {
            if (encode == null || encode.equals("")) {
                // 默认以utf-8形式
                encode = "utf-8";
            }
            while ((len = inputStream.read(b)) != -1) {
                sb.append(new String(b, 0, len, encode));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static void exitCleanAction(Context context) {
        if (null == context) {
            context = DanluApplication.get();
        }
        PushEngine.newInstance().unsetAlias(agent.getLoginUser().getUserId());
        PushEngine.newInstance().unSetTopic(CommonConst.TOPIC_PREFIX + agent.getLoginUser().getCompanyId());
        PushEngine.newInstance().unSetTopic(CommonConst.TAG_ENVELOP + agent.getLoginUser().getCompanyId());
        PushEngine.newInstance().pausePush();
        ActivePhoneProcess.isShowBefore = false;
        // 关闭账号统计
        MobclickAgent.onProfileSignOff();
        // 清除密码
        PreferenceUtils utils = new PreferenceUtils(context);
        utils.clearPassword();
        // 清除登录用户
        agent.clearLoginUser();
        // 跳转到登录画面
        ActivityUtils.startLoginActivity(context);

        // 清空mainactiviy的角标对象
        MainMenuActivity.shopCart = null;

        // 3.0以下系统clear task和new task没能清理Activity，将MainMenuActivity结束掉
        Activity parent = ((Activity) context).getParent();
        if (null != parent && !parent.isFinishing()) {
            parent.finish();
        }
        // 清除缓存
        CommonUtils.clearAllCgrPrtBrd(context.getApplicationContext());
        ACache.get(context.getApplicationContext()).remove("count");
        ACache.get(context.getApplicationContext()).remove("isClick");
    }

    /**
     * 兼容android 7.0系统
     *
     * @param view
     *         ->
     */
    public static Activity getActivity(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                // ViewGroup decorView = (ViewGroup) getWindow ().getDecorView ();
                Field field = view.getContext().getClass().getDeclaredField("mPhoneWindow");
                field.setAccessible(true);
                Object obj = field.get(view.getContext());
                java.lang.reflect.Method m1 = obj.getClass().getMethod("getContext");
                return (Activity) (m1.invoke(obj));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return getNormalActivity(view);
    }

    private static Activity getNormalActivity(View view) {
        Context context = view.getContext();
        return getActByContext(context);
    }

    public static Activity getActByContext(Context context) {
        while (context instanceof ContextWrapper) {
            if (context instanceof Activity) {
                return (Activity) context;
            }
            context = ((ContextWrapper) context).getBaseContext();
        }
        return null;
    }

    public static void hideStatusBar(Activity activity) {
        WindowManager.LayoutParams attrs = activity.getWindow().getAttributes();
        attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        activity.getWindow().setAttributes(attrs);
    }

    public static void showStatusBar(Activity activity) {
        WindowManager.LayoutParams attrs = activity.getWindow().getAttributes();
        attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
        activity.getWindow().setAttributes(attrs);
    }

    /**
     * 品牌缓存自定义list
     *
     * @author wzf
     */
    public static class CachingArrayList extends ArrayList<ThreeTuple<String, String, String>> implements Serializable {
        private static final long serialVersionUID = -5870453758049194201L;

        @Override
        public boolean add(ThreeTuple<String, String, String> object) {
            for (int i = 0; i < this.size(); i++) {
                ThreeTuple<String, String, String> threeTuple = this.get(i);
                if (threeTuple.getFirstValue().equals(object.getFirstValue())) {
                    this.remove(i);
                    i--;
                }
            }
            return super.add(object);
        }
    }
}
